package top.kuxiao.crmserver.utils;

import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import top.kuxiao.crmserver.pojo.AccountManager;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token 管理
 * 创建 token
 * 解析 token
 * 判断 token 是否有效
 *      jwt(java web token)有两种实现方式
 *          jws(json web signature)
 *          jwe(json web encryption)
 */
@Component
public class JWTUtilK {

    //有效期
    private static final long exp = 30*60*1000;// 30分钟
    //加密密钥
    private static final String secret = "kuxiao";

    //创建token obj->str
    public static String createToken(Object data){
        JwtBuilder jwtBuilder = Jwts.builder();//jwt编码器
        Map<String, Object> map = new HashMap<>();
        map.put("data",data);
        jwtBuilder.setClaims(map)//数据
                .setSubject(String.valueOf(data.hashCode()))//主题
                .setIssuedAt(new Date())//发布日期
                .setExpiration(new Date(System.currentTimeMillis()+exp))//过期时间
                .signWith(SignatureAlgorithm.HS512, secret);//签名算法
        return jwtBuilder.compact();
    }

    //解析token str-obj
    public static Map<String,Object> parseToken(String token){
        JwtParser jwtParser = Jwts.parser();//jwt解析器
        jwtParser.setSigningKey(secret);//解析密钥
        return (Map<String, Object>) jwtParser.parseClaimsJws(token).getBody().get("data");
    }

    //判断token有效性
    public static boolean isValid(String token){
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        AccountManager am = new AccountManager();
        am.setId(1001);
        am.setName("张三");
        System.out.println("am = " + am);

        String token = createToken(am);
        System.out.println("token = " + token);

        System.out.println("isValid(token) = " + isValid(token));
        Map<String, Object> map = parseToken(token);
        System.out.println("parseToken(token) = " + map);

        AccountManager am2 = new AccountManager();
        am2.setId((Integer) map.get("amId"));
        am2.setName((String) map.get("amName"));
        am2.setPassword((String) map.get("amPassword"));
        am2.setRealname((String) map.get("amRealname"));
        am2.setPhone((Long) map.get("amPhone"));
        System.out.println("am2 = " + am2);

        System.out.println("(am == am2) = " + (am == am2));
        System.out.println("am.equals(am2) = " + am.equals(am2));
    }

}
